use super::file_util::get_content_type;
use super::load_config::Settings;

use log::error;
use std::borrow::Cow;
use std::fs::File;
use std::io::Read;
use tao::platform::windows::IconExtWindows;
use tao::window::Icon;
use tao::{
    dpi::LogicalSize,
    event::{Event, WindowEvent},
    event_loop::{ControlFlow, EventLoop},
    window::WindowBuilder,
};
use wry::http::Response;
use wry::WebViewBuilder;

pub fn show(setting: Settings) {
    let entry = setting.option.entry;
    let width = setting.window.width;
    let height = setting.window.height;

    // 加载 PNG 文件作为图标
    // let icon = load_icon_from_png(concat!(
    //     env!("CARGO_MANIFEST_DIR"),
    //     "/src/assets/html-runner.png"
    // ))
    // .expect("Failed to load icon");
    let icon = Icon::from_path(
        concat!(env!("CARGO_MANIFEST_DIR"), "/src/assets/html-runner.ico"),
        None,
    )
    .map_err(|e| {
        error!("加载ICO图标失败: {}", e);
        e
    })
    .ok(); // 将Result转换为Option

    let event_loop = EventLoop::new();
    let window = WindowBuilder::new()
        .with_title("Colt Html Runner")
        .with_inner_size(LogicalSize::new(width, height)) // 设置窗口大小
        .with_window_icon(icon) // 设置窗口图标
        .build(&event_loop)
        .unwrap();

    // 创建一个可以在多个线程间共享的 WebView 引用
    let webview = std::sync::Arc::new(std::sync::Mutex::new(None::<wry::WebView>));
    let webview_clone = webview.clone();

    let builder = WebViewBuilder::new()
        .with_devtools(true)
        .with_asynchronous_custom_protocol(
            "html-runner".into(),
            move |_webview_id, request, responder| {
                // 从 URL 提取文件路径
                let url = request.uri().to_string();
                let url = url.split('?').next().unwrap_or(&url); // 去掉 ? 及其后的查询参数
                let file_path = url
                    .strip_prefix("html-runner://system/")
                    .map(|p| {
                        // 自动补全目录索引文件
                        let mut path = p.to_string();
                        if path.ends_with('/') || path == "" {
                            path.push_str("index.html");
                        }
                        format!("./{}/{}", entry, path)
                    })
                    .unwrap_or_default();
                std::thread::spawn(move || {
                    // 读取文件
                    match File::open(&file_path) {
                        Ok(mut file) => {
                            let mut contents = Vec::new();
                            if file.read_to_end(&mut contents).is_ok() {
                                // 根据文件扩展名设置 Content-Type
                                let content_type = get_content_type(&file_path);

                                let mut builder = Response::builder()
                                    .status(200)
                                    .header("Content-Length", contents.len().to_string()); // 添加内容长度头

                                // 设置缓存策略（静态资源缓存1小时）
                                if let Some(ext) = std::path::Path::new(&file_path).extension() {
                                    if let Some(ext) = ext.to_str() {
                                        if matches!(ext.to_lowercase().as_str(), "js" | "css") {
                                            builder = builder
                                                .header("Cache-Control", "public, max-age=3600");
                                        }
                                    }
                                }

                                builder = builder.header("Content-Type", content_type); // 直接设置，无需判断

                                let response = builder.body(Cow::Owned(contents)).unwrap();
                                responder.respond(response);
                            } else {
                                let response = Response::builder()
                                    .status(500)
                                    .header("Content-Type", "text/plain")
                                    .body(Cow::Owned(b"Failed to read file".to_vec()))
                                    .unwrap();
                                responder.respond(response);
                            }
                        }
                        Err(_) => {
                            let response = Response::builder()
                                .status(404)
                                .header("Content-Type", "text/plain")
                                .body(Cow::Owned(
                                    format!("File not found: {}", file_path).into_bytes(),
                                ))
                                .unwrap();
                            responder.respond(response);
                        }
                    }
                });
            },
        )
        .with_ipc_handler(move |msg| {
            // println!("Received message from JS: {:?}", msg);
            // 获取 WebView 并发送响应
            if let Ok(webview) = webview_clone.lock() {
                if let Some(webview) = webview.as_ref() {
                    let _ = webview.evaluate_script(&format!(
                        "window.receiveFromRust('Rust received: {:?}')",
                        msg
                    ));
                }
            }
        })
        .with_url("html-runner://system/index.html");

    // 保存 WebView 实例
    let webview_instance = builder.build(&window).unwrap();
    if let Ok(mut webview) = webview.lock() {
        *webview = Some(webview_instance);
    }

    event_loop.run(move |event, _, control_flow| {
        *control_flow = ControlFlow::Wait;

        match event {
            Event::WindowEvent {
                event: WindowEvent::CloseRequested,
                ..
            } => {
                // println!("The close button was pressed; stopping");
                *control_flow = ControlFlow::Exit
            }
            Event::MainEventsCleared => {
                window.request_redraw();
            }
            Event::RedrawRequested(_) => {
                // Redraw the application.
            }
            _ => (),
        }
    });
}
